package com.huatai.exchange.bootup.task;

import com.faneui.common.exception.BusinessException;
import com.faneui.common.utils.DateFormatUtils;
import com.faneui.common.utils.ListUtils;
import com.faneui.service.Env;
import com.huatai.exchange.dal.model.ExcCustDataFile;
import com.huatai.exchange.facade.Contents;
import com.huatai.exchange.integration.base.service.WorkDayService;
import com.huatai.exchange.integration.support.service.ScheduleBatchService;
import com.huatai.exchange.service.ExcCustDataFileService;
import com.huatai.support.facade.bean.ScheduleBatchVo;
import com.huatai.support.facade.bean.schedule.RegisterScheduleBatchReq;
import com.huatai.support.facade.enums.TaskDealStatus;
import com.huatai.support.facade.enums.TaskScheduleType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 *
 */
@Component
public class AutoCreateCustDataBatchTask {

    private static final Logger logger = LoggerFactory.getLogger(AutoCreateCustDataBatchTask.class);

    @Autowired
    private ExcCustDataFileService custDataFileService;

    @Autowired
    private ScheduleBatchService scheduleBatchService;

    @Autowired
    private WorkDayService workDayService;

    @Autowired
    private Env env;

    @Value("${server.port}")
    private String businSystemCode;

    @Scheduled(fixedDelay = 30 * 60 * 1000)
    public void run() {
        if (env.isLocal() || env.isDev()) {
            return;
        }
        String date = DateFormatUtils.yyyyMMdd.format(new Date());
        try {
            ExcCustDataFile param = new ExcCustDataFile();
            param.setStatus(Contents.boolean_true);
            param.setNextDate(date);
            List<ExcCustDataFile> tasks = custDataFileService.queryExcCustDataFileList(param);
            if (ListUtils.isEmpty(tasks)) {
                logger.info("当天无任务或任务已全部执行");
                return;
            }
            for (ExcCustDataFile task : tasks) {
                // 校验 昨天的任务 是否执行 成功

                String startTime = task.getBeginTime();
                if (Integer.valueOf(DateFormatUtils.HHmmss.format(new Date())) < Integer.valueOf(startTime)) {
                    logger.info("任务【{}】未到时间", task.getTaskName());
                    continue;
                }
                String interval = task.getInterval();
                //
                String nextDate = workDayService.getWorkDayNextWorkDay(date);
                if (Contents.interval_first_workdate.equals(interval)) {
                    nextDate = getNextFirstWorkDay(date);
                }

                RegisterScheduleBatchReq req = new RegisterScheduleBatchReq();

                req.setBusinId(Contents.busin_cust_data_id + task.getId());
                req.setTaskName(task.getTaskName());
                req.setBusinSystemCode(businSystemCode);
                // 参数编辑
                req.setProperties(task.getJsonProperties());
                req.setSystemPort(businSystemCode);

                req.setHttpMethod("GET");
                // 增加日期
                req.setInterfaceUrl(Contents.cust_excute_url + task.getId() + "?occurDate=" + date);

                // 增加
                req.setTaskScheduleType(TaskScheduleType.day_more);
                req.setDealInterval(60 * 60 * 1000);
                req.setErrorTimes(100);

                scheduleBatchService.registerScheduleBatch(req);
                //  注册 任务

                custDataFileService.modifyCustDataFile(task.getId(), nextDate, date);
            }
        } catch (Exception ex) {
            logger.error("", ex);
        }
    }

    /**
     * 获取下一个 交易日的第一天
     */
    private String getNextFirstWorkDay(String workdate) throws BusinessException {
        String nextFirstWorkDate = null;
        try {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(DateFormatUtils.yyyyMMdd.parse(workdate));
            do {
                calendar.add(Calendar.DATE, 1);
                nextFirstWorkDate = DateFormatUtils.yyyyMMdd.format(calendar.getTime());
            } while (!workDayService.checkIsWorkDay(nextFirstWorkDate));
            nextFirstWorkDate = workDayService.getNextWorkDay(nextFirstWorkDate);
        } catch (Exception ex) {
            BusinessException.throwBusinessException(ex);
        }
        return nextFirstWorkDate;
    }
}
